import wx
import copy
import os
from decimal import Decimal as Dec

from DataTool import DataTool
from Table4rate import Table4rate
from DiaTable4ChangeRate import DiaTable4ChangeRate


class DiaMainChangeBook(wx.Dialog):

    ListCtrlNames = ['序列', '分册名称', '分册状态']
    ListCtrlWidths = [60, 500, 60]
    BtnNames = ['修改', '上移', '下移', '拷贝', '删除', '显示/隐藏', '确定', '取消',]
    Fun = ['self.OnDataRowUp', 'self.OnDataRowUp', 'self.OnDataRowDown', 'self.OnCopy', 
           'self.OnDelete', 'self.OnDisplay', 'self.OnSave', 'self.OnCancel', ]
    def __init__(self, parent, title, *args, **kwargs):
        self.data = copy.deepcopy(kwargs.get('data', list()))
        self.ret = dict()
        super().__init__(parent, -1, title)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        datasizer = wx.BoxSizer(wx.VERTICAL)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)

        self.InitUI(datasizer)
        self.InitBtn(btnsizer)

        mainsizer.Add(datasizer, 0, flag=wx.ALL|wx.EXPAND, border=0)
        mainsizer.Add(btnsizer, 0, flag=wx.ALL|wx.ALIGN_RIGHT, border=0)

        self.InitListCtrl()

        self.SetSizer(mainsizer)
        mainsizer.Fit(self)
        mainsizer.SetSizeHints(self)
    
    def InitUI(self, sizer):
        listctrl = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL, size=(500, 300), name='ratebook')
        sizer.Add(listctrl, flag=wx.EXPAND|wx.ALL, border=5)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectRateBook, listctrl)

    def InitBtn(self, sizer):
        for index, name in enumerate(self.BtnNames):
            btn = wx.Button(self, -1, label=name, name=name+'btn')
            self.Bind(wx.EVT_BUTTON, eval(self.Fun[index]), btn)
            # self.Bind(wx.EVT_BUTTON, self.OnCopy, btn)
            sizer.Add(btn, 0, flag=wx.ALL|wx.EXPAND, border=5)

    def InitListCtrl(self):
        listctrl = self.FindWindowByName('ratebook')
        for index, name in enumerate(self.ListCtrlNames):
            listctrl.InsertColumn(index, name)
            listctrl.SetColumnWidth(index, self.ListCtrlWidths[index])
        self.Refresh()

    def Refresh(self):
        listctrl = self.FindWindowByName('ratebook')
        listctrl.DeleteAllItems()
        for row, rowv in enumerate(self.data):
            index = listctrl.InsertItem(row, str(row))
            for col, value in enumerate(rowv):
                if col == 0:
                    listctrl.SetItem(index, col, str(index+1))
                elif col == 1:
                    listctrl.SetItem(index, col, str(value['分册名称']))
                else:
                    break
            if len(rowv) <= 3:
                value = '显示'
            elif rowv[3] == 'CLOSE':
                value = '隐藏'
            else:
                value = '显示'
            listctrl.SetItem(index, 2, value)
        self.ReitData()

    def ReitData(self):
        for index, row in enumerate(self.data):
            row[0] = index

    def OnSelectRateBook(self, event):
        self.RateBookIndex = event.GetIndex()

    def OnDataRowUp(self, evnet):
        listctrl = self.FindWindowByName('ratebook')
        if hasattr(self, 'RateBookIndex'):
            row = self.RateBookIndex
            if row != 0:
                temprow = self.data[row]
                self.data.insert(row - 1, temprow)
                self.data.pop(row + 1)
            self.Refresh()
            listctrl.Select(row - 1)

    def OnDataRowDown(self, event):
        listctrl = self.FindWindowByName('ratebook')
        if hasattr(self, 'RateBookIndex'):
            row = self.RateBookIndex
            if row != len(self.data) - 1:
                temprow = self.data[row]
                self.data.insert(row + 2, temprow)
                self.data.pop(row)
            self.Refresh()
            listctrl.Select(row + 1)

    def OnCopy(self, event):
        listctrl = self.FindWindowByName('ratebook')
        if hasattr(self, 'RateBookIndex'):
            row = self.RateBookIndex
            temprow = copy.deepcopy(self.data[row])
            self.data.insert(row, temprow)
            self.Refresh()
            listctrl.Select(row + 1)

    def OnDelete(self,event):
        listctrl = self.FindWindowByName('ratebook')
        if hasattr(self, 'RateBookIndex'):
            row = self.RateBookIndex
            self.data.pop(row)
            self.Refresh()
            listctrl.Select(row - 1)

    def OnDisplay(self, event):
        listctrl = self.FindWindowByName('ratebook')
        if hasattr(self, 'RateBookIndex'):
            row = self.RateBookIndex
            if self.data[row][3] == 'CLOSE':
                self.data[row][3] = 'DISPLAY'
            else:
                self.data[row][3] = 'CLOSE'
            self.Refresh()
            listctrl.Select(row)

    def OnSave(self, event):
        self.EndModal(retCode=1)
    
    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.data
        else:
            return 5101






if __name__ == "__main__":
    import os
    from decimal import Decimal
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    class MyFrame(wx.Frame):
        def __init__(self):
            super().__init__(None, -1, 'haha', size=(200, 100))
            btn = wx.Button(self, -1, 'baba', size=(10, 10))
            self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        def OnClick(self, event):
            data = [
                    [0, {'分册名称': '13123'}, 'data', 'CLOSE'],
                    [1, {'分册名称': '222'}, 'data', 'OPEN' ],
                    [2, {'分册名称': '1333123'}, 'data', 'CLOSE'],
                    [3, {'分册名称': '4444'}, 'data', 'OPEN'],
                    [4, {'分册名称': '5555'}, 'data', 'CLOSE'],
                   ]
            dia = DiaMainChangeBook(self, 'haha', name='haha', data=data, path=BASE_DIR)
            modal = dia.ShowModal()
            print(modal)
            dia.Destroy()

    app = wx.App()
    MyFrame().Show()
    app.MainLoop()